<template>
  <div class="jnpf-content-wrapper">
    <div class="jnpf-content-wrapper-center">
      <div class="jnpf-content-wrapper-search-box">
        <BasicForm
          @register="registerSearchForm"
          :schemas="searchSchemas"
          @advanced-change="redoHeight"
          @submit="handleSearchSubmit"
          @reset="handleSearchReset"
          class="search-form">
        </BasicForm>
      </div>
      <div class="jnpf-content-wrapper-content">
        <BasicTable @register="registerTable" v-bind="getTableBindValue" ref="tableRef" @columns-change="handleColumnChange">
          <template #tableTitle>
            <a-button type="link" preIcon="icon-ym icon-ym-btn-download" @click="handleDownload">导出</a-button>
            <!-- <a-button type="link" preIcon="icon-ym icon-ym-btn-download" @click="openExportModal(true, { columnList: state.exportList })">导出</a-button> -->
          </template>
          <template #bodyCell="{ column, record, index }">
            <template v-for="(item, index) in childColumnList" v-if="childColumnList.length">
              <template v-if="column?.id?.includes('-') && item.children && item.children[0] && column.key === item.children[0]?.dataIndex">
                <ChildTableColumn
                  :data="record[item.prop]"
                  :head="item.children"
                  @toggleExpand="toggleExpand(record, item.prop + `Expand`)"
                  @toDetail="toDetail"
                  :expand="record[item.prop + `Expand`]"
                  :key="index" />
              </template>
            </template>
            <template v-if="column.jnpfKey === 'relationForm'">
              <p class="link-text" @click="toDetail(column.modelId, record[column.dataIndex + `_id`])"> {{ record[column.dataIndex] }}</p>
            </template>
            <template v-if="column.jnpfKey === 'inputNumber'">
              <jnpf-input-number v-model:value="record[column.prop]" :precision="column.precision" :thousands="column.thousands" disabled detailed />
            </template>
            <template v-if="column.jnpfKey === 'calculate'">
              <jnpf-calculate
                v-model:value="record[column.prop]"
                :isStorage="column.isStorage"
                :precision="column.precision"
                :thousands="column.thousands"
                detailed />
            </template>
            <template v-if="column.key === 'action' && !record.top">
              <TableAction :actions="getTableActions(record)" />
            </template>
          </template>
          <template #summary v-if="state.cacheList.length">
            <a-table-summary fixed>
              <a-table-summary-row>
                <a-table-summary-cell :index="0">合计</a-table-summary-cell>
                <a-table-summary-cell :index="1">{{ rbdwNum }}</a-table-summary-cell>
                <a-table-summary-cell :index="2">{{ xmslNum }}</a-table-summary-cell>
                <a-table-summary-cell :index="3">{{ gcNum }}</a-table-summary-cell>
                <a-table-summary-cell :index="4">{{ hwNum }}</a-table-summary-cell>
                <a-table-summary-cell :index="5">{{ fwNum }}</a-table-summary-cell>
                <a-table-summary-cell :index="6">{{ zlNum }}</a-table-summary-cell>
                <a-table-summary-cell :index="7">{{ otherNum }}</a-table-summary-cell>
              </a-table-summary-row>
            </a-table-summary>
          </template>
        </BasicTable>
      </div>
    </div>
    <Form ref="formRef" @reload="reload" />
    <ExportModal @register="registerExportModal" @download="handleDownload" />
    <RelationDetail ref="relationDetailRef" />
  </div>
</template>

<script lang="ts" setup>
  import { getList, del, exportData, batchDelete } from './helper/api';
  import { getConfigData } from '/@/api/onlineDev/visualDev';
  import { getDictionaryDataSelector } from '/@/api/systemData/dictionary';
  import { getDataInterfaceRes } from '/@/api/systemData/dataInterface';
  import { ref, reactive, onMounted, toRefs, computed, unref, nextTick, toRaw } from 'vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useOrganizeStore } from '/@/store/modules/organize';
  import { useUserStore } from '/@/store/modules/user';
  import { BasicModal, useModal } from '/@/components/Modal';
  import { usePopup } from '/@/components/Popup';
  import { ScrollContainer } from '/@/components/Container';
  import { BasicLeftTree, TreeActionType } from '/@/components/Tree';
  import { BasicForm, useForm } from '/@/components/Form';
  import { BasicTable, useTable, TableAction, ActionItem, TableActionType } from '../Table';
  import Form from './Form.vue';
  // 有关联表单详情：开始
  import RelationDetail from '/@/views/common/dynamicModel/list/detail/index.vue';
  // 有关联表单详情：结束
  import ChildTableColumn from '/@/views/common/dynamicModel/list/ChildTableColumn.vue';
  import { ExportModal } from '/@/components/CommonModal';
  import { downloadByUrl } from '/@/utils/file/download';
  import { useRoute } from 'vue-router';
  import { FilterOutlined } from '@ant-design/icons-vue';
  import { getSearchFormSchemas } from '/@/components/FormGenerator/src/helper/transform';
  import { cloneDeep } from 'lodash-es';
  import columnList from './helper/columnList';
  import searchList from './helper/searchList';
  import superQueryJson from './helper/superQueryJson';
  import { dyOptionsList, systemComponentsList } from '/@/components/FormGenerator/src/helper/config';
  import { thousandsFormat } from '/@/utils/jnpf';
  import dayjs from 'dayjs';

  interface State {
    formFlowId: string;
    flowList: any[];
    config: any;
    columnList: any[];
    printListOptions: any[];
    columnBtnsList: any[];
    customBtnsList: any[];
    treeFieldNames: any;
    leftTreeData: any[];
    leftTreeLoading: boolean;
    treeActiveId: string;
    treeActiveNodePath: any;
    columns: any[];
    complexColumns: any[];
    childColumnList: any[];
    exportList: any[];
    cacheList: any[];
    currFlow: any;
    isCustomCopy: boolean;
    candidateType: number;
    currRow: any;
    workFlowFormData: any;
    expandObj: any;
    columnSettingList: any[];
    searchSchemas: any[];
    treeRelationObj: any;
    resetFromTree: boolean;
  }
  // 上报单位
  const rbdwNum = ref(0);
  // 项目数量
  const xmslNum = ref(0);
  // 工程
  const gcNum = ref(0);
  // 货物
  const hwNum = ref(0);
  // 服务
  const fwNum = ref(0);
  // 租赁
  const zlNum = ref(0);
  // 其他
  const otherNum = ref(0);
  const route = useRoute();
  const { createMessage, createConfirm } = useMessage();
  const { t } = useI18n();
  const organizeStore = useOrganizeStore();
  const userStore = useUserStore();
  const userInfo = userStore.getUserInfo;

  const [registerExportModal, { openModal: openExportModal, closeModal: closeExportModal, setModalProps: setExportModalProps }] = useModal();
  const [registerImportModal, { openModal: openImportModal }] = useModal();
  const [registerSuperQueryModal, { openModal: openSuperQuery }] = useModal();
  const formRef = ref<any>(null);
  const tableRef = ref<Nullable<TableActionType>>(null);
  const detailRef = ref<any>(null);
  const relationDetailRef = ref<any>(null);
  const defaultSearchInfo = {
    modelId: '561206679820047109',
    menuId: '572406059134626629',
    // menuId: route.meta.modelId as string,
    // moduleId:'568781558375260869',
    superQueryJson: '',
    dataType: 0,
    queryType: 3,
  };
  const searchInfo = reactive({
    ...cloneDeep(defaultSearchInfo),
  });
  const state = reactive<State>({
    formFlowId: '',
    flowList: [],
    config: {},
    columnList: [],
    printListOptions: [],
    columnBtnsList: [],
    customBtnsList: [],
    treeFieldNames: {
      children: 'children',
      title: 'fullName',
      key: 'id',
      isLeaf: 'isLeaf',
    },
    leftTreeData: [],
    leftTreeLoading: false,
    treeActiveId: '',
    treeActiveNodePath: [],
    columns: [],
    complexColumns: [], // 复杂表头
    childColumnList: [],
    exportList: [],
    cacheList: [],
    currFlow: {},
    isCustomCopy: false,
    candidateType: 1,
    currRow: {},
    workFlowFormData: {},
    expandObj: {},
    columnSettingList: [],
    searchSchemas: [],
    treeRelationObj: null,
    resetFromTree: false,
  });
  const { flowList, childColumnList, searchSchemas } = toRefs(state);
  const [registerSearchForm, { updateSchema, resetFields, setFieldsValue, submit: searchFormSubmit }] = useForm({
    baseColProps: { span: 6 },
    showActionButtonGroup: true,
    showAdvancedButton: true,
    compact: true,
  });
  const [registerTable, { reload, setLoading, getFetchParams, getSelectRowKeys, redoHeight, clearSelectedRowKeys }] = useTable({
    api: getList,
    immediate: false,
    clickToRowSelect: false,
    afterFetch: data => {
      const list = data.map(o => ({
        ...o,
        ...state.expandObj,
      }));
      state.cacheList = cloneDeep(list);
      state.cacheList.forEach(o => {
        o.agency1 = Number(o.agency1);
        o.engineering = Number(o.engineering);
        o.goods = Number(o.goods);
        o.other = Number(o.other);
        o.projectsNums = Number(o.projectsNums);
        o.rentOut = Number(o.rentOut);
        o.service = Number(o.service);
      });
      // 上报单位
      rbdwNum.value = state.cacheList.length;
      // 项目数量
      xmslNum.value = state.cacheList.reduce((accumulator, currentValue) => accumulator + currentValue.projectsNums, 0);
      // 工程
      gcNum.value = state.cacheList.reduce((accumulator, currentValue) => accumulator + currentValue.engineering, 0);
      // 货物
      hwNum.value = state.cacheList.reduce((accumulator, currentValue) => accumulator + currentValue.goods, 0);
      // 服务
      fwNum.value = state.cacheList.reduce((accumulator, currentValue) => accumulator + currentValue.service, 0);
      // 租赁
      zlNum.value = state.cacheList.reduce((accumulator, currentValue) => accumulator + currentValue.rentOut, 0);
      // 其他
      otherNum.value = state.cacheList.reduce((accumulator, currentValue) => accumulator + currentValue.other, 0);
      console.log('state.cacheList', state.cacheList);
      setLoading(false);
      return list;
    },
  });

  const getTableBindValue = computed(() => {
    let columns = state.complexColumns;
    const data: any = {
      pagination: { pageSize: 20 }, //有分页
      searchInfo: unref(searchInfo),
      defSort: {
        sort: 'desc', //sort
        sidx: 'projects_nums', //取defaultSidx
      },
      columns,
      bordered: true,
      //   actionColumn: {
      //     width: 150,
      //     title: '操作',
      //     dataIndex: 'action',
      //   },
    };
    return data;
  });
  const getSummaryColumn = computed(() => {
    let defaultColumns = state.complexColumns;
    // 处理列固定
    if (state.columnSettingList?.length) {
      for (let i = 0; i < defaultColumns.length; i++) {
        inner: for (let j = 0; j < state.columnSettingList.length; j++) {
          if (defaultColumns[i].dataIndex === state.columnSettingList[j].dataIndex) {
            defaultColumns[i].fixed = state.columnSettingList[j].fixed;
            defaultColumns[i].visible = state.columnSettingList[j].visible;
            break inner;
          }
        }
      }
      defaultColumns = defaultColumns.filter(o => o.visible);
    }
    let columns: any[] = [];
    for (let i = 0; i < defaultColumns.length; i++) {
      if (defaultColumns[i].jnpfKey === 'table') {
        columns.push(...defaultColumns[i].children);
      } else {
        columns.push(defaultColumns[i]);
      }
    }
    const leftFixedList = columns.filter(o => o.fixed === 'left');
    const rightFixedList = columns.filter(o => o.fixed === 'right');
    const noFixedList = columns.filter(o => o.fixed !== 'left' && o.fixed !== 'right');
    return [...leftFixedList, ...noFixedList, ...rightFixedList];
  });
  const getColumnSum = computed(() => {
    const sums: any[] = [];
    const summaryField: any = ['reporting_unit']; //取summaryField
    const isSummary = key => summaryField.includes(key);
    const useThousands = key => unref(getSummaryColumn).some(o => o.__vModel__ === key && o.thousands);
    unref(getSummaryColumn).forEach((column, index) => {
      let sumVal = state.cacheList.reduce((sum, d) => sum + getCmpValOfRow(d, column.prop), 0);
      if (!isSummary(column.prop)) sumVal = '';
      sumVal = Number.isNaN(sumVal) ? '' : sumVal;
      const realVal = sumVal && !Number.isInteger(sumVal) ? Number(sumVal).toFixed(2) : sumVal;
      sums[index] = useThousands(column.prop) ? thousandsFormat(realVal) : realVal;
    });

    return sums;
  });

  function init() {
    state.config = {};
    searchInfo.menuId = route.meta.modelId as string;
    state.columnList = columnList;
    setLoading(true);
    getSearchSchemas();
    getColumnList();
    nextTick(() => {
      // 有搜索列表
      searchFormSubmit();
    });
  }
  function getSearchSchemas() {
    const schemas = getSearchFormSchemas(searchList);
    state.searchSchemas = schemas;
    schemas.forEach(cur => {
      const config = cur.__config__;
      if (dyOptionsList.includes(config.jnpfKey)) {
        if (config.dataType === 'dictionary') {
          if (!config.dictionaryType) return;
          getDictionaryDataSelector(config.dictionaryType).then(res => {
            updateSchema([{ field: cur.field, componentProps: { options: res.data.list } }]);
          });
        }
        if (config.dataType === 'dynamic') {
          if (!config.propsUrl) return;
          const query = { paramList: config.templateJson || [] };
          getDataInterfaceRes(config.propsUrl, query).then(res => {
            const data = Array.isArray(res.data) ? res.data : [];
            updateSchema([{ field: cur.field, componentProps: { options: data } }]);
          });
        }
      }
      if (config.defaultCurrent) {
        if (config.jnpfKey === 'organizeSelect' && userInfo.organizeIdList?.length) {
          cur.defaultValue = cur.componentProps.multiple ? [userInfo.organizeIdList] : userInfo.organizeIdList;
        }
        if (config.jnpfKey === 'depSelect' && userInfo.departmentId) {
          cur.defaultValue = cur.componentProps.multiple ? [userInfo.departmentId] : userInfo.departmentId;
        }
        if (config.jnpfKey === 'userSelect' && userInfo.userId) {
          cur.defaultValue = cur.componentProps.multiple ? [userInfo.userId] : userInfo.userId;
        }
      }
    });
  }
  function getColumnList() {
    // 没有开启列表权限
    let columnList = state.columnList;
    state.exportList = columnList;
    const columns = columnList.map(o => ({
      ...o,
      title: o.label,
      dataIndex: o.prop,
      align: o.align,
      fixed: o.fixed == 'none' ? false : o.fixed,
      sorter: o.sortable,
      width: o.width || 100,
    }));
    state.columns = columns.filter(o => o.prop.indexOf('-') < 0);
    getComplexColumns(columns);
  }
  function getComplexColumns(columnList) {
    let list: any[] = [];
    for (let i = 0; i < columnList.length; i++) {
      const e = columnList[i];
      if (!e.prop.includes('-')) {
        list.push(e);
      } else {
        let prop = e.prop.split('-')[0];
        let vModel = e.prop.split('-')[1];
        let label = e.label.split('-')[0];
        let childLabel = e.label.replace(label + '-', '');
        let newItem = {
          align: 'center',
          jnpfKey: 'table',
          prop,
          label,
          title: label,
          dataIndex: prop,
          children: [],
        };
        e.dataIndex = vModel;
        e.title = childLabel;
        if (!state.expandObj.hasOwnProperty(prop + `Expand`)) state.expandObj[prop + `Expand`] = false;
        if (!list.some(o => o.prop === prop)) list.push(newItem);
        for (let i = 0; i < list.length; i++) {
          if (list[i].prop === prop) {
            list[i].children.push(e);
            break;
          }
        }
      }
    }
    // 行内分组展示
    getMergeList(list);

    state.complexColumns = list;
    state.childColumnList = list.filter(o => o.jnpfKey === 'table');
  }
  function getMergeList(list) {
    list.forEach(item => {
      if (item.children && item.children.length) {
        item.children.forEach((child, index) => {
          if (index == 0) {
            child.customCell = () => ({
              rowspan: 1,
              colspan: item.children.length,
              class: 'child-table-box',
            });
          } else {
            child.customCell = () => ({
              rowspan: 0,
              colspan: 0,
            });
          }
        });
      }
    });
  }
  function toggleExpand(row, field) {
    row[field] = !row[field];
  }
  // 关联表单查看详情
  function toDetail(modelId, id) {
    if (!id) return;
    getConfigData(modelId).then(res => {
      if (!res.data || !res.data.formData) return;
      const formConf = JSON.parse(res.data.formData);
      formConf.popupType = 'general';
      const data = { id, formConf, modelId };
      relationDetailRef.value?.init(data);
    });
  }
  function handleColumnChange(data) {
    state.columnSettingList = data;
  }
  function getTableActions(record): ActionItem[] {
    return [];
  }
  // 导出
  function handleDownload() {
    let data = {
      dataType: 0,
      selectKey: ['reportingUnit', 'projectsNums', 'engineering', 'goods', 'service', 'rentOut', 'other'],
    };
    let query = { ...getFetchParams(), ...data };
    exportData(query)
      .then(res => {
        setExportModalProps({ confirmLoading: false });
        if (!res.data.url) return;
        downloadByUrl({ url: res.data.url });
        closeExportModal();
      })
      .catch(() => {
        setExportModalProps({ confirmLoading: false });
      });
  }
  //合计方法
  function getCmpValOfRow(row, key) {
    const summaryField: any = ['reporting_unit']; //取summaryField
    const isSummary = key => summaryField.includes(key);
    if (!summaryField.length || !isSummary(key)) return 0;
    const target = row[key];
    if (!target) return 0;
    const data = isNaN(target) ? 0 : Number(target);
    return data;
  }
  function handleSearchReset() {
    clearSelectedRowKeys();
    if (!state.resetFromTree) updateSearchFormValue();
    if (state.resetFromTree) state.resetFromTree = false;
  }
  function handleSearchSubmit(data) {
    clearSelectedRowKeys();
    let obj = {
      ...defaultSearchInfo,
      superQueryJson: searchInfo.superQueryJson,
      ...data,
    };
    Object.keys(searchInfo).map(key => {
      delete searchInfo[key];
    });
    for (let [key, value] of Object.entries(obj)) {
      searchInfo[key.replaceAll('-', '_')] = value;
    }
    console.log(searchInfo);
    if (searchInfo['starttime']) {
      let list = searchInfo['starttime'];
      searchInfo['startTime'] = dayjs(list[0]).format('YYYY-MM-DD');
      searchInfo['endTime'] = dayjs(list[1]).format('YYYY-MM-DD');
    }
    reload({ page: 1 });
  }
  function updateSearchFormValue() {
    if (!state.treeActiveId) return searchFormSubmit();
    let queryJson: any = {};
    const isMultiple = !state.treeRelationObj ? false : state.treeRelationObj.searchMultiple;
    //多级左侧树，需要拼父级->转为查询参数
    if (state.treeRelationObj && state.treeRelationObj.jnpfKey && ['organizeSelect', 'cascader', 'areaSelect'].includes(state.treeRelationObj.jnpfKey)) {
      const currValue = state.treeActiveNodePath.map(o => o[state.treeFieldNames.key]);
      queryJson = { '': isMultiple ? [currValue] : currValue };
    } else {
      queryJson = { '': isMultiple ? [state.treeActiveId] : state.treeActiveId };
    }
    // 有搜索列表
    setFieldsValue(queryJson);
    searchFormSubmit();
  }

  onMounted(() => {
    init();
  });
</script>
